# !/usr/bin/env python
# -*- coding:utf-8 -*-
# @FileName : smallest_k.py
# @Time     : 2024/2/17 23:22
# @Author   : Robot-Zsj
"""
description: 
"""
import heapq


def smallest_k(nums, k):
    if len(nums) <= k:
        return nums
    heap = []
    for i in range(len(nums)):
        if i < k:
            heap.append(nums[i])  # 先将k个数字加入到heap
        else:
            heapq.heapify(heap)  # 堆栈heap
            if heap[0] < nums[i]:  # 如果最小堆的第一个值小于nums[i]，那么heap[0]将被新的数字nums[i]替换
                heapq.heapreplace(heap, nums[i])
    return heap


print(smallest_k([10, 2, 12, 3, 5, 7], 4))
